package com.exchange.plugin.webSocket;

import java.io.IOException;

import org.tio.server.ServerTioConfig;
import org.tio.websocket.server.WsServerStarter;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.IPlugin;

public class WebsocketStarter implements IPlugin{

	public static WsServerStarter wsServerStarter;
	public static ServerTioConfig serverTioConfig;

	
	public WebsocketStarter() {
		try {
			wsServerStarter = new WsServerStarter(ServerConfig.SERVER_PORT, MyWsMsgHandler.me);
		} catch (IOException e) {
			e.printStackTrace();
		}
		serverTioConfig = wsServerStarter.getServerTioConfig();
		serverTioConfig.setName(ServerConfig.PROTOCOL_NAME);
		serverTioConfig.setServerAioListener(MyServerAioListener.me);
		//设置ip监控
		serverTioConfig.setIpStatListener(MyIpStatListener.me);
		//设置ip统计时间段
		serverTioConfig.ipStats.addDurations(ServerConfig.IpStatDuration.IPSTAT_DURATIONS);
		//设置心跳超时时间
		serverTioConfig.setHeartbeatTimeout(ServerConfig.HEARTBEAT_TIMEOUT);
		
		if (PropKit.getInt("ws.use.ssl", 1) == 1) {
			//如果你希望通过wss来访问，就加上下面的代码吧，不过首先你得有SSL证书（证书必须和域名相匹配，否则可能访问不了ssl）
//			String keyStoreFile = "classpath:config/ssl/keystore.jks";
//			String trustStoreFile = "classpath:config/ssl/keystore.jks";
//			String keyStorePwd = "214323428310224";
			String keyStoreFile = PropKit.get("ssl.keystore", null);
			String trustStoreFile = PropKit.get("ssl.truststore", null);
			String keyStorePwd = PropKit.get("ssl.pwd", null);
			try {
				serverTioConfig.useSsl(keyStoreFile, trustStoreFile, keyStorePwd);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	
//	public static void start() throws Exception {
//		WebsocketStarter appStarter = new WebsocketStarter(ServerConfig.SERVER_PORT, MyWsMsgHandler.me);
//		appStarter.wsServerStarter.start();
//	}

	
	public ServerTioConfig getServerTioConfig() {
		return serverTioConfig;
	}

	public WsServerStarter getWsServerStarter() {
		return wsServerStarter;
	}


	@Override
	public boolean start() {
		try {
			wsServerStarter.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}


	@Override
	public boolean stop() {
		return false;
	}
	

}
